<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/20/24
 * Time: 2:00 PM
 */


namespace App\Services;

use App\Models\WechatGallery;

class GalleryService
{

    /**
     * 获取图库列表
     *
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList($params)
    {
        $pageSize   = $params['page_size'] ?? 50;
        $picName    = $params['pic_name'] ?? '';
        $categoryId = $params['category_id'] ?? '';

        $query = WechatGallery::query();

        if ($picName) {
            $query->where('pic_name', 'like', '%' . $picName . '%');
        }
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        $list = $query->paginate($pageSize);

        return $list;
    }


    /**
     * 获取所有标题
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAll()
    {
        return WechatGallery::query()->select('id', 'title')->get();
    }


    /**
     * 更新标题
     *
     * @param $params
     * @return bool
     */
    public function save($params)
    {
        $id         = $params['id'] ?? 0;
        $picName    = $params['pic_name'] ?? '';
        $picUrl     = $params['pic_url'] ?? '';
        $categoryId = $params['category_id'] ?? 0;
        if (!$picName || !$picUrl) {

            return false;
        }

        if ($id) {
            $gallery              = WechatGallery::query()->find($id);
            $gallery->pic_name    = $picName;
            $gallery->pic_url     = $picUrl;
            $gallery->category_id = $categoryId;

            return $gallery->save();
        } else {
            $gallery              = new WechatGallery;
            $gallery->pic_name    = $picName;
            $gallery->pic_url     = $picUrl;
            $gallery->category_id = $categoryId;
            $gallery->admin_id    = request()->admin->id;

            return $gallery->save();
        }
    }


    /**
     * 删除标题
     *
     * @param $id
     * @return bool|mixed|null
     */
    public function delete($id)
    {
        $gallery = WechatGallery::query()->find($id);

        // 删除图片
        if ($picUrl = $gallery->pic_url ?? '') {
            (new OssService())->deleteFile($picUrl);
        }

        return $gallery->delete();
    }
}
